var app = getApp();
var _this;
Page({
  data: {
    orderInfo: null,//订单信息
    isInterpay: 0,//是否积分抵扣
    address: null,//地址
    totalPrice: 0,//商品总价
    totalNum: 0,//商品总数
    com_list: [],//商品列表
    isAgent: false,//是否是合伙人订单
    orderData: null,//订单信息
    remark: '',
    time: null,
    surplus: ''
  },

  /**
   * 积分提示模态框
   * 
   */
  showTip(){
    wx.showModal({
      title: '积分使用规则',
      content: `1、100积分=1元\n2、积分能购买所有有“积分兑换”标志的商品`,
    })
  },

  /**
   * 获取商品列表
   * @type method
   * @return Arrary
   */
  getComList: function (isAgent) {
    if (isAgent) {
      this.getAgentInfo().then(function (data) {
        var data = {
          image: data.bosimgurl[0],
          title: data.commodityname,
          price: data.price.toFixed(2),
          num: 1
        }
        _this.setData({
          com_list: [data]
        })
      })
      return ''
    }
    return app.buyCar
  },

  /**
   * 未支付订单倒计时
   */
  setInterval: function () {
    var interval = setInterval(function () {
      var order_date_str = _this.data.orderData.order.date
      var order_date = new Date(order_date_str.replace(/-/g, '/'))
      var subtime = (order_date.getTime() + 30 * 60 * 1000) - new Date().getTime();
      var temp_time = {}
      var hour = Math.floor(subtime / (60 * 60 * 1000))
      var min = Math.floor((subtime / (60 * 1000)) % 60)
      var sec = Math.floor((subtime / 1000) % 60)
      temp_time.hour = hour < 10 ? '0' + hour : hour
      temp_time.min = min < 10 ? '0' + min : min
      temp_time.sec = sec < 10 ? '0' + sec : sec
      _this.setData({
        time: temp_time
      })
      if (subtime <= 0) {
        clearInterval(interval)
      }
    }, 1000)
  },


  /**
   * 获取商品总数量
   * @type method
   * @return Number
   */
  getTotalComNum: function () {
    var num = 0
    this.getComList().forEach(function (item) {
      num += parseInt(item.num)
    })
    return num
  },


  /**
    * 获取商品总价格
    * @type method
    * @return Number
    */
  getTotalComPrice: function () {
    if (!_this.data.isAgent) {
      var price = 0
      this.getComList().forEach(function (item) {
        price += parseFloat(item.price) * parseFloat(item.num)
      })
      return price.toFixed(2)
    }
  },


  /**
   * 获取是否积分支付
   */
  getIsInterpay: function (res) {
    if (res.detail.value) {
      _this.setData({
        isInterpay: 1
      })
    } else {
      _this.setData({
        isInterpay: 0
      })
    }
    _this.getPayprice();
  },


  /**
   * 获取订单价格
   * @type request
   */
  getPayprice: function () {
    if (_this.payPrice) return _this.payPrice
    if (_this.data.isCollage) {
      wx.request({
        url: app.globalData.data_url + '/GPD/getCollagePrice.do',
        data: {
          session_id: app.globalData.sessionId,
          collage_id: _this.collage.id,
          num: _this.getComList()[0].num,
          address_id: _this.data.address.id
        },
        success: function (res) {
          wx.hideLoading()
          if (res.data.code > 0) {
            wx.showToast({
              title: res.data.message,
              image: '/images/close.png'
            })
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              })
            }, 1500)
            return
          }
          res.data.payprice = res.data.payprice.toFixed(2)
          res.data.paysum = res.data.paysum.toFixed(2)
          res.data.freight_fee = res.data.freight_fee.toFixed(2)
          _this.setData({
            orderInfo: res.data,
            surplus: (res.data.free_freight_price - res.data.payprice).toFixed(2)
          })
        }
      })
      return
    }
    wx.request({
      url: app.globalData.data_url +
      '/GPD/getPrice.do?isInterpay=' +
      _this.data.isInterpay +
      '&address_id=' +
      _this.data.address.id +
      '&session_id=' +
      app.globalData.sessionId,
      method: 'post',
      data: _this.getComList().map(function (item) {
        return { commodity_id: item.id, num: item.num }
      }),
      success: function (res) {
        wx.hideLoading()
        if (res.data.code > 0) {
          wx.showToast({
            title: res.data.message,
            image: '/images/close.png'
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 1500)
          return
        }
        res.data.payprice = res.data.payprice.toFixed(2)
        res.data.paysum = res.data.paysum.toFixed(2)
        res.data.freight_fee = res.data.freight_fee.toFixed(2)
        _this.setData({
          orderInfo: res.data,
          surplus: (res.data.free_freight_price - res.data.payprice).toFixed(2)
        })
      }
    })
  },


  /**
   * 获取默认地址
   * @type request
   * @retrn Promise
   */
  getDefaultAddress: function () {
    return new Promise(function (resolve, reject) {
      wx.request({
        url: app.globalData.data_url + "/GPD/getDefaultAddress.do",
        data: {
          session_id: app.globalData.sessionId
        },
        success: function (res) {
          _this.setData({
            address: res.data.default_ra
          })
          resolve(res.data.default_ra)
        }
      })
    })
  },

  getRemark: function (res) {
    _this.setData({
      remark: res.detail.value
    })
  },


  // /**
  //  * 选择是否积分抵扣
  //  * @type method
  //  */
  // chooseInteration: function (e) {
  //   wx.showLoading({
  //     title: '加载中',
  //   })
  //   _this.setData({
  //     isInterpay: Number(e.detail.value)
  //   })
  //   this.getPayprice()
  // },


  /**
   * 生成订单
   * @type request
   * @retrun Promise 
   */
  createOrder: function () {
    return new Promise(function (resolve, reject) {
      if (_this.data.orderData) {
        resolve(_this.data.orderData)
        return
      }
      if (_this.data.isCollage) {
        wx.request({
          url: app.globalData.data_url + '/GPD/getCollageOrder.do',
          data: {
            session_id: app.globalData.sessionId,
            collage_id: _this.collage.id,
            num: _this.getComList()[0].num,
            address_id: _this.data.address.id,
            remark: _this.data.remark
          },
          success: function (res) {
            _this.setData({
              orderData: res.data
            })
            resolve(res.data)
          }
        })
        return
      }
      if (_this.data.isAgent) {
        wx.request({
          url: app.globalData.data_url + '/GPD/getAgentOrder.do',
          data: {
            session_id: app.globalData.sessionId,
            sharekey: app.globalData.fatherid
          },
          success: function (res) {
            resolve(res.data)
          }
        })
      } else {
        wx.request({
          url: app.globalData.data_url +
          '/GPD/getCommodityOrder.do?isInterpay=' +
          _this.data.isInterpay +
          '&address_id=' +
          _this.data.address.id +
          '&session_id=' +
          app.globalData.sessionId +
          '&remark=' +
          _this.data.remark,
          method: 'post',
          data: _this.getComList().map(function (item) {
            return { commodity_id: item.id, num: item.num }
          }),
          success: function (res) {
            _this.setData({
              orderData: res.data
            })
            resolve(res.data)
          }
        })
      }
    })
  },


  /**
   * 支付订单
   * @type request
   */
  pay: function () {
    wx.showLoading({
      title: '加载中',
    })
    this.createOrder().then(function (data) {
      _this.setInterval()
      if (data.code > 0) {
        wx.hideLoading()
        wx.showToast({
          title: data.message,
          image: '/images/close.png'
        })
        return
      }
      wx.request({
        url: app.globalData.data_url + "/GPD/pay.do",
        data: {
          session_id: app.globalData.sessionId,
          ordernumber: data.order.ordernumber
        },
        success: function (res) {
          wx.hideLoading()
          wx.requestPayment({
            ...res.data,
            success: function (res) {
              console.log(res)
              wx.redirectTo({
                url: '/pages/paySuccess/paySuccess?ordernumber=' + data.order.ordernumber,
              })
            },
            fail: function (res) {
              console.log(res)
            }
          })
        }
      })
    })
  },



  /**
   * 获取合伙人信息
   * @type request
   * @retrun Promise
   */
  getAgentInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    return new Promise(function (resolve, reject) {
      wx.request({
        url: app.globalData.data_url + '/GPD/getAgentGoods.do',
        success: function (res) {
          wx.hideLoading()
          resolve(res.data.agentcommodity)
          _this.setData({
            totalNum: 1,
            totalPrice: res.data.agentcommodity.price.toFixed(2)
          })
        }
      })
    })
  },


  /**
   * 跳转地址页面
   * @type method
   */
  goAddress: function () {
    if (_this.data.orderData) return
    wx.navigateTo({
      url: '/pages/address/address?forBuy=true',
    })
  },

  onLoad: function (options) {
    _this = this
    if (options.isAgent) {
      this.getComList(true)
      this.setData({
        isAgent: options.isAgent
      })
      return
    }
    if (options.data) {
      this.collage = JSON.parse(options.data)
      this.setData({
        isCollage: true
      })
    }
    this.setData({
      com_list: this.getComList(),
      totalNum: this.getTotalComNum(),
      totalPrice: this.getTotalComPrice()
    })
  },


  onShow: function () {
    if (!this.data.isAgent) {
      wx.showLoading({
        title: '加载中',
      })
      this.getDefaultAddress().then(function (res) {
        if (res == null) {
          wx.hideLoading();
          wx.showToast({
            title: '请先添加地址',
            image: '/images/close.png'
          })
          setTimeout(function () {
            _this.goAddress()
          }, 1500)
          return
        }
        _this.getPayprice()
      })
    }
  },
  onUnload: function () {

  }
})